<?php

namespace app\controller;

use app\lib\pay\weixin\lib\database\WxPayUnifiedOrder;
use app\lib\pay\weixin\lib\WxPayNativePay;
use think\annotation\Route;
use app\lib\Show;

use app\business\Pay as PayBis;
use think\facade\Cache;

class Pay extends AuthBase {

    public function genToken() {
        $app = config("appuser.{$this->appId}");
        $data = [
            time(),
            $this->appId,
            $app['key']
        ];
        $token = md5(implode($app['stitching_symbol'], $data));
        return $token;
    }

    /**
     * 支付demo
     */
    public function index() {
        $notify = new WxPayNativePay();
        $input = new WxPayUnifiedOrder();
        $input->SetBody('ShopM商城');
        $input->SetAttach('欢迎选购');
        $input->SetOut_trade_no('test' . date('YmdHis'));
        $input->SetTotal_fee('1');
        $input->SetTime_start(date('YmdHis'));
        $input->SetTime_expire(date('YmdHis', time() + 300));
        $input->SetGoods_tag('test');
        $input->SetNotify_url('http://pay.singwa666.com/pay/notify/weixin');
        $input->SetTrade_type('NATIVE');
        $input->SetProduct_id('123456789');

        $result = $notify->GetPayUrl($input);
        if ($result['return_code']) {
            return Show::error($result['return_msg']);
        }

        $url2 = $result['code_url'];
        echo "<img src='" . url('qcode/index', ['data' => $url2]) . "'>";
        //echo "<img src='http://120.25.227.106:9090/qcode/index.html?data=weixin%3A%2F%2Fwxpay%2Fbizpayurl%3Fpr%3DyfUgY5H'>";
    }

    /**
     * 下单API
     * @return string
     * @Route("unifiedOrder", method="POST")
     */
    public function unifiedOrder() {
        $params = input('param.');
        $body = input('param.body', '', 'trim');
        $goods_id = input('param.goods_id', '', 'intval');
        if (empty($body) || empty($goods_id)){
            return Show::error('商品描述和产品id不能为空');
        }

        try {
            $result = (new PayBis())->unifiedOrder($this->appId, $this->payType, $params);
        } catch (\Exception $e) {
            return Show::error($e->getMessage());
        }
        if (!$result) {
            return Show::error('下单失败');
        }
        return Show::success($result);
    }

    /**
     * 对外API，订单查询
     * @Route("getOrder", method="POST")
     */
    public function getOrder() {
        try {
            $orderId = input('param.order_id', '', 'trim');
            if (!$orderId) {
                return Show::error('order_id参数错误');
            }
            $result = (new PayBis())->getOrder($orderId, $this->appId);
        } catch (\Exception $e) {
            return Show::error();
        }
        if (!$result) {
            return Show::error();
        }
        return Show::success($result);
    }
}
